package yrq.leetcode.solution;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Stack;

/**
 * @author ：Excalibur
 * @create ：2020-08-30 12:07
 * @description：
 */
@SpringBootTest
public class reverseWords {

    @Test
    public void main() {
        String originString = "Let's take LeetCode contest";
        String reverseString = reverseWordsB(originString);
        System.out.println(reverseString);
    }

    public String reverseWords(String s) {
        if (s == null || s.equals(""))
            return s;

        String[] words = s.split(" ");
        ArrayList<String> reverseWords = new ArrayList<>();
        for (String word: words) {
            Stack< Character > stack = new Stack < Character > ();
            char[] ch = word.toCharArray();
            for (int i = 0; i < word.length(); i++) {
                stack.push(ch[i]);
            }
            int k = 0;
            while (!stack.isEmpty()) {
                ch[k++] = stack.pop();
            }
            reverseWords.add(String.copyValueOf(ch));
        }
        return String.join(" ", reverseWords);
    }

    public String reverseWordsB(String s) {
        char[] a = s.toCharArray();
        int n = a.length;
        int left = 0;
        int right = 0;
        char temp;
        for (int i = 0; i < n; i++) {
            if (a[i] == ' ') {
                right = i - 1;
                while (left < right) {
                    temp = a[left];
                    a[left++] = a[right];
                    a[right--] = temp;
                }
                left = i + 1;
            }
        }
        right = n - 1;
        while (left < right) {
            temp= a[left];
            a[left++] = a[right];
            a[right--] = temp;
        }
        return new String(a);
    }
}
